/*
 * NumberListFile.cpp
 *
 *  Created on:  Jun 12, 2009
 *      Author:  Zach Riggle A37627537
 *      Project: CSE410 Project 2
 */

#include <fstream>
#include <sstream>
#include "NumberListFile.h"
#include "Misc.h"

RegularExpression NumberListFile::number("^-?[0-9]+$");

NumberListFile::NumberListFile() {
}

NumberListFile::NumberListFile(string fn) {
    load(fn);
}

NumberListFile::~NumberListFile() {
}

int NumberListFile::load(string fn) {

    // Open the file
    ifstream fin;
    fin.open(fn.c_str(), ifstream::in);

    // Did the open succeed?
    if (!fin.is_open()) {
        error("Could not open " << fn << " for reading");
        return -1;
    }

    // Make sure that there is data to read
    streambuf *pbuf = fin.rdbuf();
    if (pbuf->in_avail() == 0) {
        warn("No data available to read from file " << fn);
        return -1;
    }

    // Clear the list
    numberList.clear();

    // Iterate through the file's contents
    int n=0;
    string s;
    while (!fin.eof() && !fin.fail()) {

        // Read the data
        getline(fin,s);
        s = trim(s);

        // Make sure it's a number, and ONLY a number.
        if (s.size() < 1){
        	warn("Found empty line, skipping");
        	continue;
        }
        if (!number.match(s)) {
            error("Invalid data in file: \"" << s << "\"");
            continue;
        }

        // Add it to the vector
        n = atoi(s.c_str());
        numberList.push_back(n);
        debug("Read " << s << " (" << n << ") from file");
    }

    // Close the file
    fin.close();

    return numberList.size();
}

int NumberListFile::save(string fn) {
    // Open the file
    ofstream fout;
    fout.open(fn.c_str(), ofstream::out | ofstream::trunc);

    if (!fout.is_open()) {
        error("Could not open " << fn << " for writing");
        return -1;
    }

    // Iterate
    vector<int>::iterator iter;
    for (iter = numberList.begin(); iter != numberList.end(); iter++) {
        fout << *iter << endl;
        debug("Wrote " << *iter << " to the file");
    }

    // Close the file
    fout.close();

    // Return the number written to file
    return numberList.size();
}

void NumberListFile::setNumbers(vector<int> v) {
    numberList.clear();
    numberList = v;
}

vector<int> NumberListFile::getNumbers() {
    return numberList;
}
